/**
 * 设备管理工具
 * 用于在登录时记录设备信息
 */
import { recordLoginDevice } from "@/api/modules/device"
import { generateDeviceFingerprint } from "./fingerprint"
import { getDeviceInfo } from "./detector"

/**
 * 记录登录设备信息
 * @param {number} userId - 用户ID
 * @param {string} sessionToken - 会话令牌
 * @param {string} ipAddress - IP地址
 * @param {string} location - 登录地点
 * @returns {Promise} 记录结果
 */
export async function recordCurrentLoginDevice(userId, sessionToken, ipAddress = '', location = '') {
  try {
    const deviceInfo = getDeviceInfo()
    const deviceId = generateDeviceFingerprint()

    const data = {
      userId,
      deviceId,
      deviceName: deviceInfo.deviceName,
      deviceType: deviceInfo.deviceType,
      browser: deviceInfo.browser,
      os: deviceInfo.os,
      loginMethod: 'PASSWORD',
      ipAddress: ipAddress || '',
      location: location || '',
      sessionToken: sessionToken || ''
    }

    const response = await recordLoginDevice(data)
    return response
  } catch (error) {
    console.error('记录登录设备失败:', error)
    return null
  }
}

/**
 * 获取当前设备ID
 * @returns {string} 设备ID
 */
export function getCurrentDeviceId() {
  return generateDeviceFingerprint()
}

/**
 * 获取当前设备信息（用于显示）
 * @returns {Object} 设备信息
 */
export function getCurrentDeviceInfo() {
  const deviceInfo = getDeviceInfo()
  const deviceId = generateDeviceFingerprint()
  return {
    ...deviceInfo,
    deviceId
  }
}
